import React, { useState,useRef, useEffect } from 'react'
import { Button,Card,Modal,Form,Input,Select, message } from 'antd';
import MyTable from './components/Table'
import { reqUsers,reqRoles,reqUserDelete,reqUserCreate,reqUserModify } from '../../api/index';
import './User.css'

const {Option}=Select

/* 
  用户管理路由
*/
export default function User() {

  // const user_form=Form.useForm()
  const user_form = useRef()
  const [modalVisible,setModalVisible] = useState({visible:false,type:'create'})
  const [data,setData] = useState([])
  const [user,setUser] = useState({})
  const [roles,setRoles] = useState([])
  const title=(<Button type='primary' onClick={()=>{setModalVisible({visible:true,type:'create'});setUser({})}}>创建用户</Button>)

  const createUser=()=>{
    user_form.current.validateFields().then(values=>{
      if(modalVisible.type!=='create')values.id=user._id
      console.log(values)
      let requestFunc=modalVisible.type==='create'?reqUserCreate:reqUserModify
      requestFunc(values).then(res=>{
        console.log(res)
        setModalVisible({visible:false,type:''})
        message.success(res.msg)
        setData([])
      }).catch(err=>{
        setModalVisible({visible:false,type:''})
        message.error(err)
      })
    })

  }

  useEffect(()=>{
    async function getData(){
      let res=await reqUsers()
      let roles=await reqRoles()
      setData(res)
      setRoles(roles)
    }
    if(data.length===0)getData()
  },[data])

  return (
    <div className='user'>
      <Card title={title}>
        <MyTable data={data} roles={roles} reqUserDelete={reqUserDelete} user={user} setUser={setUser} setData={setData} setModalVisible={setModalVisible}></MyTable>
      </Card>
      <Modal 
        onCancel={()=>setModalVisible({visible:false,type:''})} 
        onOk={createUser} 
        visible={modalVisible.visible} 
        title={modalVisible.type==='create'?'创建用户':'修改用户'}
      >
        <Form key={user._id} ref={user_form} labelCol={{span:4}} wrapperCol={{span:18}} 
        initialValues={modalVisible.type==='create'?{username:'',phone:'',email:'',role_id:''}:
        {username:user.username,phone:user.phone,email:user.email,role_id:user.role_id}}>
          <Form.Item name='username' colon label='用户名'  rules={[{required:true,message:'必填项'},{max:20,message:'不能大于20个字符'},{min:5,message:'不能低于4个字符'}]}>
            <Input placeholder='请输入用户名'></Input>
          </Form.Item>
          {
            modalVisible.type!=='create'?null:
            <Form.Item name='password' colon label='密码' rules={[{required:true,message:'必填项'},{max:20,message:'不能大于20个字符'},{min:6,message:'不能低于6个字符'}]}>
              <Input type='password' placeholder='请输入密码'></Input>
            </Form.Item>
          }
          <Form.Item name='phone' colon label='手机号' rules={[{required:true,message:'必填项'},{pattern:/^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,message:'不符合手机号规则'}]}>
            <Input placeholder='请输入手机号'></Input>
          </Form.Item>
          <Form.Item name='email' colon label='邮箱' rules={[{required:true,message:'必填项'},{type:'email',message:'不符合邮箱规则'}]}>
            <Input placeholder='请输入邮箱'></Input>
          </Form.Item>
          <Form.Item name='role_id' colon label='角色' rules={[{required:true,message:'必填项'}]}>
            <Select  type='select' placeholder='请选择角色'>
              {
                roles.map(i=>{
                  return <Option key={i._id} value={i._id}>{i.name}</Option>
                })
              }
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
